from src import utils
import json
import requests


def get_available_appointment_dates(cookies, target_date, locationId, categoryId, visaType, visaSubType, token):
    applicantCount = '1'
    dataSource = 'WEB_BLS'
    missionId = ''
    url = 'https://spain.blscn.cn/CHN/BLSAppointment/GetAvailableAppointmentDates?locationId=' + locationId + '&categoryId=' + categoryId + '&visaType=' + visaType + '&visaSubType=' + visaSubType + '&applicantCount=' + applicantCount + '&dataSource=' + dataSource + '&missionId=' + missionId
    headers = utils.get_headers(requestverificationtoken=token)
    res = requests.post(url, headers=headers, cookies=cookies)
    print(res.content)
    json_obj = json.loads(res.content)
    date_arr = json_obj['ad']
    found_json = next(
        filter(lambda person: person["DateText"] == target_date and person["SingleSlotAvailable"] == True, date_arr),
        None)
    return found_json != None

def get_available_slots_by_date(cookies, appointmentDate, locationId, categoryId, visaType, visaSubType, token):
    applicantCount = '1'
    dataSource = 'WEB_BLS'
    missionId = ''
    url = 'https://spain.blscn.cn/CHN/blsappointment/GetAvailableSlotsByDate?appointmentDate=' + appointmentDate + '&locationId=' + locationId + '&categoryId=' + categoryId + '&visaType=' + visaType + '&visaSubType=' + visaSubType + '&applicantCount=' + applicantCount + '&dataSource=' + dataSource + '&missionId=' + missionId
    headers = utils.get_headers(requestverificationtoken=token)
    res = requests.post(url, headers=headers, cookies=cookies)
    json_obj = json.loads(res.content)
    list_slot = list(filter(lambda person: person["Count"] > 0, json_obj))
    return list_slot
